package com.situ.shoplook.common.util;

import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * 功能：
 *
 * @author 千堆雪
 * @version 1.0.0
 * <p>
 * created by 千堆雪 on 2024/8/24, last modified by 千堆雪 on 2024/8/24
 */
@Component
public class SpringUtils implements ApplicationContextAware, ServletContextAware {
    private static ApplicationContext ac;
    private static ServletContext sc;

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        ac = applicationContext;
    }

    public static void setApplicationContext(WebApplicationContext applicationContext) {
        ac = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        if (ac == null) {
            ServletContext sc = getServletContext();
            ac = WebApplicationContextUtils.findWebApplicationContext(sc);
        }
        return ac;
    }

    @Override
    public void setServletContext(@NonNull ServletContext servletContext) {
        sc = servletContext;
    }

    public static ServletContext getServletContext() {
        if (sc == null) {
            sc = getServletRequest().getServletContext();
        }
        return sc;
    }

    public static HttpServletRequest getServletRequest() {
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        return sra.getRequest();
    }

    public static <T> T getBean(@NonNull Class<T> clazz) {
        return ac.getBean(clazz);
    }
}
